/*********************************
 *	  GNU/openXmod-project       *
 *		 << copyleft >>          *
 * ----------------------------- *
 *	made by hignu22              *
 *		       GNU is Not Unix ! *
 *	 Keep It Simple ,Stupid !    *
 ********************************/
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void sigpoweroff(void);
static void sigreap(void);
static void sigreboot(void);
static void spawn(char *const []);
static void serialization(void);

#define XMODI	" -XmoD-init: "
#define WARN	" -XmoD-init: warning: "
#define FATAL	" -XmoD-init: fatal: "
#define ERROR	" -XmoD-init: error: "


/* Variabels for configuration 
 *  and paths to binaries   __
 *							||
 *							\/
 *	*/

static sigset_t set ;
/* Serialization */
static char *const rcserializecmd[] = { "/bin/rc.serialize", NULL };
static char *const rcjlog_p[]       = { "/bin/rc.serialize", "-w", NULL };
static char *const rcjlog_m[]       = { "/bin/rc.serialize", "-r", NULL };
/* Ohers binares */
static char *const rcinitcmd[]      = { "/bin/rc.init", NULL };
static char *const rcrebootcmd[]    = { "/bin/rc.shutdown", "reboot", NULL };
static char *const rcpoweroffcmd[]  = { "/bin/rc.shutdown", "poweroff", NULL };
 
#define TIMEO 30
#define LN(n) ( sizeof (n) / sizeof *(n) )
static struct {
	int16_t sig;
	void (*handler)(void);
} sigmap[] = {
	{ SIGUSR1, sigpoweroff },
	{ SIGCHLD, sigreap },
	{ SIGALRM, sigreap },
	{ SIGINT,  sigreboot },
};//   		 ||		//
/*	Functions\/		*/
int		 
main(void) {									// _start :
	int sig;
	size_t i;
	if (getpid() != 1) return 1;
	chdir("/"); 			
	sigfillset(&set); 			
	sigprocmask(SIG_BLOCK, &set, NULL); 
	spawn(rcinitcmd);
	spawn( rcjlog_p);
	while( 1) {
		alarm(TIMEO);
		sigwait(&set, &sig);
		for ( i = 0; i < LN(sigmap); i++ ) {
			if (sigmap[i].sig == sig	){
				sigmap[i].handler();
				break;
			}
		}
	}           return 0;
}
static void
spawn(char *const argv[]) {						// start process
	switch (fork()) {
	case 0:
		sigprocmask(SIG_UNBLOCK, &set, NULL);
		setsid();
		execvp(argv[0], argv);
		perror("execvp");
		_exit(1);
	case -1:
		perror("fork");
	}
}
static void 
sigreap( void) {								
	while (waitpid(-1, NULL, WNOHANG) > 0) ;
	alarm(TIMEO);
}

static void 
sigpoweroff(void) {	
	spawn(rcpoweroffcmd);
}

static void 
sigreboot(void) { 
	spawn(rcrebootcmd); 
}
